package Base

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
	"github.com/json-iterator/go"
	"github.com/syyongx/php2go"
	"hello/models"
	"hello/wl"
	"strings"
)

func init() {
	fmt.Println("只在加载执行一次")
	Valid=validation.Validation{}
}
func (this *BaseController)Test()  {
	fmt.Println("我是父亲Test")
}




func (this *BaseController) Prepare() {
	this.SetUserToRedis()


}

var (
		BaseModel models.BaseMode
		Valid validation.Validation
		wlErr error
	)

type BaseController struct {
	beego.Controller
	wl.Log
	Limit int
	Page int
}
//分页自动化
func (this * BaseController)PageInit()  {
	this.Page,wlErr=this.GetInt("page",1)
	this.Limit,wlErr=this.GetInt("limit",10)
	if wlErr!=nil{
		panic("分页参数错误!")
	}
}


//往Redis 里添加用户数据
func (this * BaseController)SetUserToRedis()  {
	token:=this.GetPost("token")
	if php2go.Empty(token) {
		fmt.Println("没有登陆结束")
		return
	}

	byteValue := wl.RedisGet(token.(string))


	var  jsonUser models.User
	if err := jsoniter.Unmarshal(byteValue, &jsonUser); err != nil{
		fmt.Println("错误!error: ", err)
	}

	
	if php2go.Empty(jsonUser) {
		wl.RedisSet(token.(string),jsonUser,30)
	}
}

func (this * BaseController)AjaxSuccess(a interface{}){

	this.Data["json"] =wl.AjaxSuccess(a)
	this.ServeJSON()
	this.StopRun()

}

func (this * BaseController)AjaxError(a interface{}){

	this.Data["json"] =wl.AjaxError(a)
	this.ServeJSON()
	this.StopRun()
}

func (this * BaseController)AjaxOther(a interface{}){

	this.Data["json"] =a
	this.ServeJSON()
	this.StopRun()
}



func (this * BaseController)GetPost(key string) interface{} {
	//如果通过获取的为空
	if php2go.Empty(this.GetString(key)) {
		Context:=string(this.Ctx.Input.RequestBody)

		reader := strings.NewReader(Context)
		decoder := json.NewDecoder(reader)
		params := make(map[string]interface{})
		err := decoder.Decode(&params)
		if err != nil {
			return ""
			panic("获取参数错误!")
		} else {
			fmt.Printf("%+v\n", params)
		}

		return params[key]
	}else{
		return this.GetString(key)
	}

}

func (this * BaseController) GetUser() models.User{

	token:=this.GetPost("token")
	if php2go.Empty(token) {
		this.AjaxOther(wl.AjaxLogin("登陆失败"))
	}

	byteValue := wl.RedisGet(token.(string))


	var  jsonUser models.User
	if err := jsoniter.Unmarshal(byteValue, &jsonUser); err != nil{
		fmt.Println("错误!error: ", err)
	}

	if php2go.Empty(jsonUser) {
		this.AjaxOther(wl.AjaxLogin("登陆失效果"))
	}

	return jsonUser
}



